/*
 * @Description:
 * @version:
 * @Author: 171
 * @Date: 2022-09-20 16:22:09
 * @LastEditors: 171
 * @LastEditTime: 2022-09-22 17:50:30
 */
import jwt from "jsonwebtoken";
import express, { Router, Request, Response } from "express";
import connection  from "../db";
import qs from "qs";

const validateRouter: Router = express.Router(); // 声明一个路由，获取自定义api

// 登录持久化验证接口 访问这个接口的时候 一定要访问token（前端页面每切换一次，就访问一下这个接口，查看登录是否过期）
// 先访问登录接口，得到token，再访问这个，看是否成功
const verifyToken = (req: Request, res: Response) => {
  const token: any = req.headers.authorization;
  const publicKey: any = req.body.publicKey; 
  jwt.verify(
    token,
    publicKey,
    {
      algorithms: ["RS256"],
      
    },
    (err: any, decode: any) => {
      if (err) {
        res.send(qs.stringify({ message: "invalid token", error: err, code: 2 }));
      } else {
        const { id, account }: any = decode;
        const sql = `select privateKey from my_user where id = '${id}'`;
        connection.query(sql, (err: any, result: any) => {
          if (err) {
            const errorRes = qs.stringify({ message: "error", error: err, code: 1 });
            res.send(errorRes);
          } 
          else  { 
            const privateKey = result[0].privateKey;
            const token = jwt.sign({ id, account }, privateKey, { // 设置token
              expiresIn: 60 * 60 * 24 * 30, // Eg: 60, "2 days", "10h", "7d"
              algorithm: 'RS256' //非对称加密
            });
            const dataRes = qs.stringify({ message: 'ok', token, code: 0 });
            res.send(dataRes);
          }
        });
      }
    }
  );
};

validateRouter.post('/validate', verifyToken);

export default validateRouter;
